import sensor
import image
import lcd
import time
import image
import struct
from machine import UART
from fpioa_manager import fm



lcd.init()
sensor.reset()
#sensor.set_pixformat(sensor.GRAYSCALE)  #灰度图像
sensor.set_pixformat(sensor.RGB565)      #LAB色彩
sensor.set_framesize(sensor.QVGA)
sensor.run(1)


ROI = (64, 50, 192, 100)#窗口1
ROI1 = (0, 140, 320, 20)#窗口1
ROI2 = (0, 180, 320, 20)#窗口1
ROI_TEST = (150, 110, 20, 20) #颜色检测器窗口
#red_threshold   = (0, 60, 127, 4, -1, 127)   #red
#green_threshold   = (0, 60, -128, -11, -6, 34)   #green
blue_threshold   = (17, 64, 5, -7, -7, -26)   #blue
#black_threshold   = (0, 60, 127, 4, -1, 127)   #red (255,0,0)

fm.register(10, fm.fpioa.UART1_TX, force=True) #10为tx接rx
fm.register(9, fm.fpioa.UART1_RX, force=True) #11为rx接tx

#串口发送
uart = UART(UART.UART1, 115200, 8, 1, 0, timeout=1000, read_buf_len=4096)
uart.init(115200, bits=8, parity=None, stop=1)  # init with given parameters

while True:
    sensor.set_vflip(True)
    sensor.set_hmirror(0)
    ix = 0
    iy = 0
    ih = 0
    img=sensor.snapshot()
    #blobs = img.find_blobs([red_threshold],roi = ROI)
    #blobs1 = img.find_blobs([green_threshold],roi = ROI)
    blobs2 = img.find_blobs([blue_threshold],roi = ROI)
    #blobs3 = img.find_blobs([black_threshold],roi = ROI)

    if blobs2:
        for b in blobs2:
            tmp=img.draw_rectangle(b[0:4])
            tmp=img.draw_cross(b[5], b[6])
            c=img.get_pixel(b[5], b[6])
            ix = b[5]
            iy = b[6]
            #色框宽度
            len_x = b[2]    #........................
            #print(ix,iy)

    FH = bytearray([0x2c,0x12,ix, iy,ih,0x5B])
    uart.write(FH)
    statistics=img.get_statistics(roi=ROI)

    img.draw_rectangle(ROI)


#取色器
    #statistics=img.get_statistics(roi=ROI_TEST)
    #color_l=statistics.l_mode()
    #color_a=statistics.a_mode()
    #color_b=statistics.b_mode()
    #print(color_l,color_a,color_b)
    #img.draw_rectangle(ROI_TEST, color=(255,0,0))
    lcd.display(img)
    #x = img.get_pixel(ix,iy)         #显示（10，15）像素点rgb值
    #print(x)











